package com.zzy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzy.domain.dto.PageLocalDto;
import com.zzy.domain.po.Warehouse;
import com.zzy.domain.po.WarehouseArea;
import com.zzy.domain.po.WarehouseLocal;
import com.zzy.domain.vo.PageResult;
import com.zzy.mapper.WarehouseAreaMapper;
import com.zzy.mapper.WarehouseLocalMapper;
import com.zzy.mapper.WarehouseMapper;
import com.zzy.service.WarehouseLocalService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class WarehouseLocalImpl extends ServiceImpl<WarehouseLocalMapper, WarehouseLocal> implements WarehouseLocalService {
    private final WarehouseLocalMapper warehouseLocalMapper;
    private final WarehouseMapper warehouseMapper;
    private final WarehouseAreaMapper warehouseAreaMapper;

    @Override
    public PageResult<WarehouseLocal> getPage(PageLocalDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<WarehouseLocal> list = warehouseLocalMapper.getpage(dto);
        Page<WarehouseLocal> page = (Page<WarehouseLocal>) list;
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public void add(WarehouseLocal warehouseLocal) {
        extracted(warehouseLocal);
        warehouseLocal.setCreateTime(LocalDateTime.now());
        warehouseLocalMapper.insert(warehouseLocal);
    }

    @Override
    public void updateWarehouseLocal(WarehouseLocal warehouseLocal) {
        extracted(warehouseLocal);
        warehouseLocal.setUpdateTime(LocalDateTime.now());
        warehouseLocalMapper.updateById(warehouseLocal);
    }

    private void extracted(WarehouseLocal warehouseLocal) {
        // 获取仓库信息
        Warehouse warehouse = warehouseMapper.selectById(warehouseLocal.getWarehouseId());
        if (warehouse != null) {
            warehouseLocal.setWarehouseName(warehouse.getName());
        }

        // 获取库区信息
        WarehouseArea warehouseArea = warehouseAreaMapper.selectById(warehouseLocal.getWarehouseAreaId());
        if (warehouseArea != null) {
            warehouseLocal.setWarehouseAreaName(warehouseArea.getName());
            warehouseLocal.setCategory(warehouseArea.getCategory());
        }
    }
}